Your First AI application¶

Going forward, AI algorithms will be incorporated into more and more everyday applications. For example, you might want to include an image classifier in a smart phone app. To do this, you'd use a deep learning model trained on hundreds of thousands of images as part of the overall application architecture. A large part of software development in the future will be using these types of models as common parts of applications.

In this project, you'll train an image classifier to recognize different species of flowers. You can imagine using something like this in a phone app that tells you the name of the flower your camera is looking at. In practice you'd train this classifier, then export it for use in your application. We'll be using this dataset from Oxford of 102 flower categories, you can see a few examples below.

The project is broken down into multiple steps:

  • Load the image dataset and create a pipeline.
  • Build and Train an image classifier on this dataset.
  • Use your trained model to perform inference on flower images.

We'll lead you through each part which you'll implement in Python.

When you've completed this project, you'll have an application that can be trained on any set of labeled images. Here your network will be learning about flowers and end up as a command line application. But, what you do with your new skills depends on your imagination and effort in building a dataset. For example, imagine an app where you take a picture of a car, it tells you what the make and model is, then looks up information about it. Go build your own dataset and make something new.

Import Resources¶

In [1]:
# Ignore some warnings that are not relevant (you can remove this if you prefer)
import warnings
warnings.filterwarnings('ignore')
In [31]:
%matplotlib inline
%config InlineBackend.figure_format = 'retina'

import time
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
import json

# Import TensorFlow 
import tensorflow as tf
import tensorflow_hub as hub
import tensorflow_datasets as tfds
tfds.disable_progress_bar()
In [3]:
import logging
logger = tf.get_logger()
logger.setLevel(logging.ERROR)
In [4]:
print('Using:')
print('\t\u2022 TensorFlow version:', tf.__version__)
print('\t\u2022 tf.keras version:', tf.keras.__version__)
print('\t\u2022 Running on GPU' if tf.test.is_gpu_available() else '\t\u2022 GPU device not found. Running on CPU')
Using:
	• TensorFlow version: 2.9.1
	• tf.keras version: 2.9.0
	• GPU device not found. Running on CPU

Load the Dataset¶

Here you'll use tensorflow_datasets to load the Oxford Flowers 102 dataset. This dataset has 3 splits: 'train', 'test', and 'validation'. You'll also need to make sure the training data is normalized and resized to 224x224 pixels as required by the pre-trained networks.

The validation and testing sets are used to measure the model's performance on data it hasn't seen yet, but you'll still need to normalize and resize the images to the appropriate size.

In [40]:
# TODO: Load the dataset with TensorFlow Datasets.
# TODO: Create a training set, a validation set and a test set.
(training_set, validation_set, test_set), dataset_info = tfds.load('oxford_flowers102',
                                                                   split=['train', 'validation', 'test'],
                                                                   as_supervised=True, 
                                                                   with_info=True)

Explore the Dataset¶

In [41]:
dataset_info
Out[41]:
tfds.core.DatasetInfo(
    name='oxford_flowers102',
    full_name='oxford_flowers102/2.1.1',
    description="""
    The Oxford Flowers 102 dataset is a consistent of 102 flower categories commonly occurring
    in the United Kingdom. Each class consists of between 40 and 258 images. The images have
    large scale, pose and light variations. In addition, there are categories that have large
    variations within the category and several very similar categories.
    
    The dataset is divided into a training set, a validation set and a test set.
    The training set and validation set each consist of 10 images per class (totalling 1020 images each).
    The test set consists of the remaining 6149 images (minimum 20 per class).
    
    Note: The dataset by default comes with a test size larger than the train
    size. For more info see this [issue](https://github.com/tensorflow/datasets/issues/3022).
    """,
    homepage='https://www.robots.ox.ac.uk/~vgg/data/flowers/102/',
    data_path='C:\\Users\\Semseman\\tensorflow_datasets\\oxford_flowers102\\2.1.1',
    file_format=tfrecord,
    download_size=328.90 MiB,
    dataset_size=331.34 MiB,
    features=FeaturesDict({
        'file_name': Text(shape=(), dtype=tf.string),
        'image': Image(shape=(None, None, 3), dtype=tf.uint8),
        'label': ClassLabel(shape=(), dtype=tf.int64, num_classes=102),
    }),
    supervised_keys=('image', 'label'),
    disable_shuffling=False,
    splits={
        'test': <SplitInfo num_examples=6149, num_shards=2>,
        'train': <SplitInfo num_examples=1020, num_shards=1>,
        'validation': <SplitInfo num_examples=1020, num_shards=1>,
    },
    citation="""@InProceedings{Nilsback08,
       author = "Nilsback, M-E. and Zisserman, A.",
       title = "Automated Flower Classification over a Large Number of Classes",
       booktitle = "Proceedings of the Indian Conference on Computer Vision, Graphics and Image Processing",
       year = "2008",
       month = "Dec"
    }""",
)
In [58]:
# TODO: Get the number of examples in each set from the dataset info.
num_examples_train = dataset_info.splits['train'].num_examples
num_examples_val = dataset_info.splits['validation'].num_examples
num_examples_test = dataset_info.splits['test'].num_examples                

# TODO: Get the number of classes in the dataset from the dataset info.
num_classes = dataset_info.features['label'].num_classes

print('The Dataset has a total of {:,} images, broken down to:'.format(num_examples_train + num_examples_val + num_examples_test))
print('\u2022 {:,} training_set images'.format(num_examples_train))
print('\u2022 {:,} validation_set images'.format(num_examples_val))
print('\u2022 {:,} test_set images'.format(num_examples_test))
print('\u2022 {:,} classes'.format(num_classes))
The Dataset has a total of 8,189 images, broken down to:
• 1,020 training_set images
• 1,020 validation_set images
• 6,149 test_set images
• 102 classes
In [49]:
# Sanity check 1
training_set.cardinality().numpy(), validation_set.cardinality().numpy(), test_set.cardinality().numpy()
Out[49]:
(1020, 1020, 6149)
In [50]:
# Sanity check 2
training_set.cardinality().numpy() + validation_set.cardinality().numpy() + test_set.cardinality().numpy()
Out[50]:
8189
In [43]:
# TODO: Print the shape and corresponding label of 3 images in the training set.
for image, label in training_set.take(3):
    print("Shape of the image: {} and its lable is {}".format(image.shape, label))
Shape of the image: (500, 667, 3) and its lable is 72
Shape of the image: (500, 666, 3) and its lable is 84
Shape of the image: (670, 500, 3) and its lable is 70
In [44]:
# TODO: Plot 1 image from the training set. Set the title 
# of the plot to the corresponding image label. 
for image, label in training_set.take(1):
    image = image.numpy()
    label = label.numpy()

plt.imshow(image)
plt.title('Image Label: {}'.format(label))
plt.show()

Label Mapping¶

You'll also need to load in a mapping from label to category name. You can find this in the file label_map.json. It's a JSON object which you can read in with the json module. This will give you a dictionary mapping the integer coded labels to the actual names of the flowers.

In [32]:
with open('label_map.json', 'r') as f:
    class_names = json.load(f)
In [38]:
# TODO: Plot 1 image from the training set. Set the title 
# of the plot to the corresponding class name. 
for image, label in training_set.take(1):
    image = image.numpy()
    label = label.numpy()

plt.imshow(image)
plt.title('Image Label: {}'.format(class_names[str(label)]))
plt.show()
In [39]:
# sanity check
class_names['72']
Out[39]:
'azalea'

Create Pipeline¶

In [59]:
# TODO: Create a pipeline for each set.
batch_size = 32
image_size = 224

def format_image(image, label):
    image = tf.cast(image, tf.float32)
    image = tf.image.resize(image, (image_size, image_size))
    image /= 255
    return image, label


training_batches = training_set.shuffle(num_examples_train//4).map(format_image).batch(batch_size).prefetch(1)
validation_batches = validation_set.map(format_image).batch(batch_size).prefetch(1)
testing_batches = test_set.map(format_image).batch(batch_size).prefetch(1)

Build and Train the Classifier¶

Now that the data is ready, it's time to build and train the classifier. You should use the MobileNet pre-trained model from TensorFlow Hub to get the image features. Build and train a new feed-forward classifier using those features.

We're going to leave this part up to you. If you want to talk through it with someone, chat with your fellow students!

Refer to the rubric for guidance on successfully completing this section. Things you'll need to do:

  • Load the MobileNet pre-trained network from TensorFlow Hub.
  • Define a new, untrained feed-forward network as a classifier.
  • Train the classifier.
  • Plot the loss and accuracy values achieved during training for the training and validation set.
  • Save your trained model as a Keras model.

We've left a cell open for you below, but use as many as you need. Our advice is to break the problem up into smaller parts you can run separately. Check that each part is doing what you expect, then move on to the next. You'll likely find that as you work through each part, you'll need to go back and modify your previous code. This is totally normal!

When training make sure you're updating only the weights of the feed-forward network. You should be able to get the validation accuracy above 70% if you build everything right.

Note for Workspace users: One important tip if you're using the workspace to run your code: To avoid having your workspace disconnect during the long-running tasks in this notebook, please read in the earlier page in this lesson called Intro to GPU Workspaces about Keeping Your Session Active. You'll want to include code from the workspace_utils.py module. Also, If your model is over 1 GB when saved as a checkpoint, there might be issues with saving backups in your workspace. If your saved checkpoint is larger than 1 GB (you can open a terminal and check with ls -lh), you should reduce the size of your hidden layers and train again.

In [62]:
# load the mobileNet pre-trained network from tensorflow hub.
URL = "https://tfhub.dev/google/tf2-preview/mobilenet_v2/feature_vector/4"

feature_extractor = hub.KerasLayer(URL, input_shape=(image_size, image_size,3))

# freeze the weights and biases in our pre-trained model so that we don't modify them during training
feature_extractor.trainable = False
In [99]:
# TODO: Build and train your network.
tf.keras.backend.clear_session()
model = tf.keras.Sequential([
        feature_extractor,
        tf.keras.layers.Dense(128, activation='relu'),
        tf.keras.layers.Dense(102, activation = 'softmax')
])

model.summary()
Model: "sequential"
_________________________________________________________________
 Layer (type)                Output Shape              Param #   
=================================================================
 keras_layer (KerasLayer)    (None, 1280)              2257984   
                                                                 
 dense (Dense)               (None, 128)               163968    
                                                                 
 dense_1 (Dense)             (None, 102)               13158     
                                                                 
=================================================================
Total params: 2,435,110
Trainable params: 177,126
Non-trainable params: 2,257,984
_________________________________________________________________
In [100]:
# Compile the model
model.compile(optimizer='adam',
              loss='sparse_categorical_crossentropy',
              metrics=['accuracy'])
In [101]:
# Stop training when there is no improvement in the validation loss for 5 consecutive epochs
early_stopping = tf.keras.callbacks.EarlyStopping(monitor='val_loss', patience=5, min_delta=0.01)

# Save the Model with the lowest validation loss
save_best = tf.keras.callbacks.ModelCheckpoint('./best_model.h5',
                                              monitor='val_loss',
                                              save_best_only=True)
In [102]:
# fitting the model
history = model.fit(training_batches,
                    epochs = 25,
                    validation_data=validation_batches,
                    callbacks=[early_stopping, save_best])
Epoch 1/25
32/32 [==============================] - 36s 1s/step - loss: 4.4644 - accuracy: 0.0471 - val_loss: 3.9622 - val_accuracy: 0.2118
Epoch 2/25
32/32 [==============================] - 37s 1s/step - loss: 3.1641 - accuracy: 0.3784 - val_loss: 2.7041 - val_accuracy: 0.4598
Epoch 3/25
32/32 [==============================] - 35s 1s/step - loss: 1.7485 - accuracy: 0.6931 - val_loss: 1.7757 - val_accuracy: 0.6333
Epoch 4/25
32/32 [==============================] - 35s 1s/step - loss: 0.9230 - accuracy: 0.8520 - val_loss: 1.3497 - val_accuracy: 0.7039
Epoch 5/25
32/32 [==============================] - 35s 1s/step - loss: 0.5210 - accuracy: 0.9422 - val_loss: 1.1631 - val_accuracy: 0.7235
Epoch 6/25
32/32 [==============================] - 36s 1s/step - loss: 0.3395 - accuracy: 0.9735 - val_loss: 1.1013 - val_accuracy: 0.7353
Epoch 7/25
32/32 [==============================] - 36s 1s/step - loss: 0.2365 - accuracy: 0.9882 - val_loss: 0.9831 - val_accuracy: 0.7745
Epoch 8/25
32/32 [==============================] - 40s 1s/step - loss: 0.1530 - accuracy: 0.9961 - val_loss: 0.9115 - val_accuracy: 0.7824
Epoch 9/25
32/32 [==============================] - 36s 1s/step - loss: 0.1076 - accuracy: 0.9980 - val_loss: 0.8802 - val_accuracy: 0.7824
Epoch 10/25
32/32 [==============================] - 35s 1s/step - loss: 0.0809 - accuracy: 0.9990 - val_loss: 0.8448 - val_accuracy: 0.7912
Epoch 11/25
32/32 [==============================] - 36s 1s/step - loss: 0.0591 - accuracy: 1.0000 - val_loss: 0.8144 - val_accuracy: 0.8069
Epoch 12/25
32/32 [==============================] - 36s 1s/step - loss: 0.0476 - accuracy: 1.0000 - val_loss: 0.8007 - val_accuracy: 0.8078
Epoch 13/25
32/32 [==============================] - 36s 1s/step - loss: 0.0396 - accuracy: 1.0000 - val_loss: 0.7827 - val_accuracy: 0.8147
Epoch 14/25
32/32 [==============================] - 36s 1s/step - loss: 0.0330 - accuracy: 1.0000 - val_loss: 0.7793 - val_accuracy: 0.8118
Epoch 15/25
32/32 [==============================] - 37s 1s/step - loss: 0.0282 - accuracy: 1.0000 - val_loss: 0.7725 - val_accuracy: 0.8157
Epoch 16/25
32/32 [==============================] - 38s 1s/step - loss: 0.0243 - accuracy: 1.0000 - val_loss: 0.7634 - val_accuracy: 0.8216
Epoch 17/25
32/32 [==============================] - 36s 1s/step - loss: 0.0215 - accuracy: 1.0000 - val_loss: 0.7565 - val_accuracy: 0.8176
Epoch 18/25
32/32 [==============================] - 38s 1s/step - loss: 0.0190 - accuracy: 1.0000 - val_loss: 0.7549 - val_accuracy: 0.8206
Epoch 19/25
32/32 [==============================] - 36s 1s/step - loss: 0.0170 - accuracy: 1.0000 - val_loss: 0.7512 - val_accuracy: 0.8196
Epoch 20/25
32/32 [==============================] - 36s 1s/step - loss: 0.0153 - accuracy: 1.0000 - val_loss: 0.7474 - val_accuracy: 0.8186
Epoch 21/25
32/32 [==============================] - 36s 1s/step - loss: 0.0138 - accuracy: 1.0000 - val_loss: 0.7416 - val_accuracy: 0.8225
Epoch 22/25
32/32 [==============================] - 35s 1s/step - loss: 0.0125 - accuracy: 1.0000 - val_loss: 0.7391 - val_accuracy: 0.8196
Epoch 23/25
32/32 [==============================] - 36s 1s/step - loss: 0.0114 - accuracy: 1.0000 - val_loss: 0.7380 - val_accuracy: 0.8216
Epoch 24/25
32/32 [==============================] - 37s 1s/step - loss: 0.0105 - accuracy: 1.0000 - val_loss: 0.7363 - val_accuracy: 0.8225
Epoch 25/25
32/32 [==============================] - 35s 1s/step - loss: 0.0097 - accuracy: 1.0000 - val_loss: 0.7350 - val_accuracy: 0.8245
In [103]:
# TODO: Plot the loss and accuracy values achieved during training for the training and validation set.

training_accuracy = history.history['accuracy']
validation_accuracy = history.history['val_accuracy']

training_loss = history.history['loss']
validation_loss = history.history['val_loss']

epochs_range=range(len(training_accuracy))

plt.figure(figsize=(16, 6))
plt.subplot(1, 2, 1)
plt.plot(epochs_range, training_accuracy, label='Training Accuracy')
plt.plot(epochs_range, validation_accuracy, label='Validation Accuracy')
plt.legend(loc='lower right')
plt.title('Training and Validation Accuracy')

plt.subplot(1, 2, 2)
plt.plot(epochs_range, training_loss, label='Training Loss')
plt.plot(epochs_range, validation_loss, label='Validation Loss')
plt.legend(loc='upper right')
plt.title('Training and Validation Loss')
plt.show()

Testing your Network¶

It's good practice to test your trained network on test data, images the network has never seen either in training or validation. This will give you a good estimate for the model's performance on completely new images. You should be able to reach around 70% accuracy on the test set if the model has been trained well.

In [104]:
# TODO: Print the loss and accuracy values achieved on the entire test set.

loss, accuracy = model.evaluate(testing_batches)

print('\nLoss on the TEST Set: {:,.3f}'.format(loss))
print('Accuracy on the TEST Set: {:.3%}'.format(accuracy))
193/193 [==============================] - 106s 549ms/step - loss: 0.9429 - accuracy: 0.7614

Loss on the TEST Set: 0.943
Accuracy on the TEST Set: 76.142%

Save the Model¶

Now that your network is trained, save the model so you can load it later for making inference. In the cell below save your model as a Keras model (i.e. save it as an HDF5 file).

In [106]:
# TODO: Save your trained model as a Keras model.

saved_keras_model_filepath = './my_model_1.h5'

model.save(saved_keras_model_filepath)

Load the Keras Model¶

Load the Keras model you saved above.

In [110]:
# TODO: Load the Keras model
reloaded_keras_model = tf.keras.models.load_model(saved_keras_model_filepath, custom_objects={'KerasLayer':hub.KerasLayer})

reloaded_keras_model.summary()
Model: "sequential"
_________________________________________________________________
 Layer (type)                Output Shape              Param #   
=================================================================
 keras_layer (KerasLayer)    (None, 1280)              2257984   
                                                                 
 dense (Dense)               (None, 128)               163968    
                                                                 
 dense_1 (Dense)             (None, 102)               13158     
                                                                 
=================================================================
Total params: 2,435,110
Trainable params: 177,126
Non-trainable params: 2,257,984
_________________________________________________________________

Inference for Classification¶

Now you'll write a function that uses your trained network for inference. Write a function called predict that takes an image, a model, and then returns the top $K$ most likely class labels along with the probabilities. The function call should look like:

probs, classes = predict(image_path, model, top_k)

If top_k=5 the output of the predict function should be something like this:

probs, classes = predict(image_path, model, 5)
print(probs)
print(classes)
> [ 0.01558163  0.01541934  0.01452626  0.01443549  0.01407339]
> ['70', '3', '45', '62', '55']

Your predict function should use PIL to load the image from the given image_path. You can use the Image.open function to load the images. The Image.open() function returns an Image object. You can convert this Image object to a NumPy array by using the np.asarray() function.

The predict function will also need to handle pre-processing the input image such that it can be used by your model. We recommend you write a separate function called process_image that performs the pre-processing. You can then call the process_image function from the predict function.

Image Pre-processing¶

The process_image function should take in an image (in the form of a NumPy array) and return an image in the form of a NumPy array with shape (224, 224, 3).

First, you should convert your image into a TensorFlow Tensor and then resize it to the appropriate size using tf.image.resize.

Second, the pixel values of the input images are typically encoded as integers in the range 0-255, but the model expects the pixel values to be floats in the range 0-1. Therefore, you'll also need to normalize the pixel values.

Finally, convert your image back to a NumPy array using the .numpy() method.

In [118]:
# TODO: Create the process_image function
def process_image(image):
    image = tf.cast(image, tf.float32)
    image = tf.image.resize(image, (224, 224))
    image /= 255
    image = image.numpy()
    
    return image

To check your process_image function we have provided 4 images in the ./test_images/ folder:

  • cautleya_spicata.jpg
  • hard-leaved_pocket_orchid.jpg
  • orange_dahlia.jpg
  • wild_pansy.jpg

The code below loads one of the above images using PIL and plots the original image alongside the image produced by your process_image function. If your process_image function works, the plotted image should be the correct size.

In [121]:
from PIL import Image

image_path = './test_images/wild_pansy.jpg'
im = Image.open(image_path)
test_image = np.asarray(im)

processed_test_image = process_image(test_image)

fig, (ax1, ax2) = plt.subplots(figsize=(10,10), ncols=2)
ax1.imshow(test_image)
ax1.set_title('Original Image')
ax2.imshow(processed_test_image)
ax2.set_title('Processed Image')
plt.tight_layout()
plt.show()

Once you can get images in the correct format, it's time to write the predict function for making inference with your model.

Inference¶

Remember, the predict function should take an image, a model, and then returns the top $K$ most likely class labels along with the probabilities. The function call should look like:

probs, classes = predict(image_path, model, top_k)

If top_k=5 the output of the predict function should be something like this:

probs, classes = predict(image_path, model, 5)
print(probs)
print(classes)
> [ 0.01558163  0.01541934  0.01452626  0.01443549  0.01407339]
> ['70', '3', '45', '62', '55']

Your predict function should use PIL to load the image from the given image_path. You can use the Image.open function to load the images. The Image.open() function returns an Image object. You can convert this Image object to a NumPy array by using the np.asarray() function.

Note: The image returned by the process_image function is a NumPy array with shape (224, 224, 3) but the model expects the input images to be of shape (1, 224, 224, 3). This extra dimension represents the batch size. We suggest you use the np.expand_dims() function to add the extra dimension.

In [134]:
# Experimenting to get intuition about the np.expand_dims
np.expand_dims(processed_test_image, 0).shape
Out[134]:
(1, 224, 224, 3)
In [233]:
tf.math.top_k(ps, k=1).indices.numpy().squeeze()+np.array([1])
Out[233]:
array([52])
In [242]:
# Getting the largest n values of a tensor along with their indices
keys_to_slice = list(map(str, tf.math.top_k(ps, k=1).indices.numpy().squeeze()+np.array([1])))
keys_to_slice
Out[242]:
['52']
In [194]:
# Translating the keys to their pertinent classes
{key : class_names[key] for key in keys_to_slice}
Out[194]:
{'52': 'wild pansy',
 '19': 'balloon flower',
 '65': 'californian poppy',
 '64': 'silverbush',
 '86': 'tree mallow'}
In [182]:
[class_names[key] for key in keys_to_slice]
Out[182]:
['petunia', 'peruvian lily', 'silverbush', 'black-eyed susan', 'desert-rose']

References:

  • https://stackoverflow.com/questions/9958846/converting-int-arrays-to-string-arrays-in-numpy-without-truncation
  • https://theprogrammingexpert.com/slice-dictionary-python/
  • https://www.tensorflow.org/api_docs/python/tf/math/top_k
In [239]:
# Trying all the pieces before building the function using the code from previous step
image_path = './test_images/wild_pansy.jpg'
im = Image.open(image_path)
test_image = np.asarray(im)

processed_test_image = process_image(test_image)
ps = reloaded_keras_model(np.expand_dims(processed_test_image,0))
props = tf.math.top_k(ps, k=5).values.numpy().squeeze()
labels = list(map(str, tf.math.top_k(ps, k=5).indices.numpy().squeeze()+np.array([1])))
classes = [class_names[key] for key in labels]

fig, (ax1, ax2, ax3) = plt.subplots(figsize=(20,8), ncols=3)
ax1.imshow(test_image)
ax1.set_title('Original Image')
ax2.imshow(processed_test_image)
ax2.set_title('Processed Image')
ax3.barh(classes, props)
plt.tight_layout()
plt.show()
In [240]:
# TODO: Create the predict function

def predict(image_path, model, top_k=5):
    '''
    Returns the top_k predictions of the image by the 
    trained mode along with their probabilities and numeric labels. 
    Plots the flower image and an horizontal bar chart of the predictions
    and their probabilities
    
        Parameters:
            image path, trainded model and top n predictions as per their probabilities.
            
        Returns:
            * top n probabilities of the predictions
            * top n predicted class numbers
            * top n predicted class names
            * Plots the image and the graph
    '''
    # open the image
    im = Image.open(image_path)
    # convert the image to a numpy array
    im = np.asarray(im)
    # process the image
    processed_image = process_image(im)
    # add extra dimension
    expanded_image = np.expand_dims(processed_image, 0)
    # predict the image using the model
    ps = model(expanded_image)
    
    props = tf.math.top_k(ps, k=top_k).values.numpy().squeeze()
    labels = list(map(str, tf.math.top_k(ps, k=top_k).indices.numpy().squeeze()+np.array([1])))
    classes = [class_names[key].title() for key in labels]

    fig, (ax1, ax2) = plt.subplots(figsize=(10,6),ncols=2)
    ax1.imshow(processed_image)
    ax1.set_title('Processed Image from file: {}'.format(image_path))
    ax2.barh(classes, props)
    ax2.set_title("Probabilities Associated with \n the Top {} Predictions by the model".format(top_k))
    plt.tight_layout()
    plt.show()
    
    return props, labels, classes
    

Sanity Check¶

It's always good to check the predictions made by your model to make sure they are correct. To check your predictions we have provided 4 images in the ./test_images/ folder:

  • cautleya_spicata.jpg
  • hard-leaved_pocket_orchid.jpg
  • orange_dahlia.jpg
  • wild_pansy.jpg

In the cell below use matplotlib to plot the input image alongside the probabilities for the top 5 classes predicted by your model. Plot the probabilities as a bar graph. The plot should look like this:

You can convert from the class integer labels to actual flower names using class_names.

In [210]:
np.set_printoptions(formatter={'float_kind':'{:.5f}'.format})
In [241]:
# TODO: Plot the input image along with the top 5 classes
probs, labels, classes = predict('./test_images/wild_pansy.jpg', reloaded_keras_model)

print('The top 5 predicted class labels are: {}'.format(labels))
print('The top 5 predicted class names are: {}'.format(classes))
print('The top 5 predicted class probabilities are: {}'.format(probs))
The top 5 predicted class labels are: ['52', '19', '65', '64', '86']
The top 5 predicted class names are: ['Wild Pansy', 'Balloon Flower', 'Californian Poppy', 'Silverbush', 'Tree Mallow']
The top 5 predicted class probabilities are: [0.99923 0.00019 0.00016 0.00013 0.00005]

Re-doing the Sanity Check on all the Images¶

In [222]:
import glob

images = glob.glob('./test_images/*')

for image in images:
    labels, classes, probs = predict(image, reloaded_keras_model, top_k=4)
    print('The top 4 predicted class labels are: {}'.format(labels))
    print('The top 4 predicted class names are: {}'.format(classes))
    print('The top 4 predicted class probabilities are: {}'.format(probs))
The top 4 predicted class labels are: [0.98270 0.00970 0.00164 0.00138]
The top 4 predicted class names are: ['61', '24', '46', '39']
The top 4 predicted class probabilities are: ['Cautleya Spicata', 'Red Ginger', 'Wallflower', 'Siam Tulip']
The top 4 predicted class labels are: [0.99987 0.00004 0.00003 0.00002]
The top 4 predicted class names are: ['2', '6', '97', '68']
The top 4 predicted class probabilities are: ['Hard-Leaved Pocket Orchid', 'Tiger Lily', 'Mallow', 'Bearded Iris']
The top 4 predicted class labels are: [0.41556 0.39699 0.06191 0.05885]
The top 4 predicted class names are: ['5', '59', '100', '71']
The top 4 predicted class probabilities are: ['English Marigold', 'Orange Dahlia', 'Blanket Flower', 'Gazania']
The top 4 predicted class labels are: [0.99923 0.00019 0.00016 0.00013]
The top 4 predicted class names are: ['52', '19', '65', '64']
The top 4 predicted class probabilities are: ['Wild Pansy', 'Balloon Flower', 'Californian Poppy', 'Silverbush']